package com.down.main;

import java.io.IOException;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.down.utls.FileUtils;
import com.down.utls.LayoutUtils;
import com.down.utls.ThreadPool;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.keeley.core.DownFileFetch;
import com.keeley.core.DownFileInfoBean;
import com.keeley.listen.DownListener;
import com.xiaoleilu.hutool.util.DateUtil;
import com.xiaoleilu.hutool.util.ThreadUtil;

public class Addnewdown extends Dialog {

	protected Object result;
	protected Shell shell;
	private Text txtHttpwapapkanzhicomdataapkecdcbdedaefcabapk;
	private Button btstop;
	private Button btbegin;
	public Integer downidk = null;
	private Text info;
	public static Thread refreshthread = null;

	public static void closetd() {
		System.out.println("关闭线程");
		if (null != refreshthread && refreshthread.isAlive()) {
			refreshthread.stop();
		}

	}

	/**
	 * Create the dialog.
	 * 
	 * @param parent
	 * @param style
	 */
	public Addnewdown(Shell parent, int style) {
		super(parent, style);
		setText("SWT Dialog");
	}

	/**
	 * Open the dialog.
	 * 
	 * @return the result
	 */
	public Object open() {
		createContents();
		LayoutUtils.center(shell);
		shell.open();
		shell.layout();
		Display display = getParent().getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		return result;
	}

	/**
	 * Create contents of the dialog.
	 */
	private void createContents() {
		shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.PRIMARY_MODAL);
		shell.setSize(450, 663);
		shell.setText("文件下载");
		shell.setLayout(new GridLayout(2, false));
		new Label(shell, SWT.NONE);
		new Label(shell, SWT.NONE);

		Label label = new Label(shell, SWT.NONE);
		label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		label.setText("下载地址:");

		txtHttpwapapkanzhicomdataapkecdcbdedaefcabapk = new Text(shell,
				SWT.BORDER | SWT.WRAP | SWT.V_SCROLL | SWT.MULTI);
		txtHttpwapapkanzhicomdataapkecdcbdedaefcabapk
				.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 5));
		new Label(shell, SWT.NONE);
		new Label(shell, SWT.NONE);
		new Label(shell, SWT.NONE);
		new Label(shell, SWT.NONE);

		Composite composite = new Composite(shell, SWT.NONE);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1));

		Button button = new Button(composite, SWT.NONE);
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				shell.dispose();
			}
		});
		button.setBounds(33, 18, 80, 27);
		button.setText("关 闭");

		Button button_1 = new Button(composite, SWT.NONE);
		button_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				addandbegin();
			}
		});
		button_1.setText("下 载");
		button_1.setBounds(139, 18, 80, 27);

		btstop = new Button(composite, SWT.NONE);
		btstop.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				stopme();
			}
		});
		btstop.setEnabled(false);
		btstop.setBounds(237, 18, 80, 27);
		btstop.setText("停 止");

		btbegin = new Button(composite, SWT.NONE);
		btbegin.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				startme();
			}
		});
		btbegin.setEnabled(false);
		btbegin.setText("开 始");
		btbegin.setBounds(334, 18, 80, 27);

		info = new Text(shell, SWT.BORDER | SWT.READ_ONLY | SWT.WRAP | SWT.V_SCROLL | SWT.MULTI);
		GridData gd_info = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1);
		gd_info.heightHint = 434;
		info.setLayoutData(gd_info);
		refreshthread = new Thread() {

			public void run() {
				while (true) {
					ThreadUtil.sleep((long) 1300);
					if (null != downidk) {
						final String l = Db.findFirst("select * from down where id=?;", downidk).getStr("logs");
						if (!shell.isDisposed()) {
							shell.getDisplay().asyncExec(new Runnable() {
								public void run() {
									info.setText(null == l ? "" : l);
								}
							});
						}
					}
				}
			}
		};
		refreshthread.start();
	}

	protected void startme() {
		// TODO Auto-generated method stub
		if (null != downidk) {
			ThreadPool.startbyid(downidk, shell);
		}
	}

	protected void stopme() {
		// TODO Auto-generated method stub
		if (null != downidk) {
			ThreadPool.stopbyid(downidk, shell);
		}
	}

	protected void addandbegin() {
		// TODO Auto-generated method stub
		final String urlt = txtHttpwapapkanzhicomdataapkecdcbdedaefcabapk.getText().trim();

		Record e = new Record();

		String fname = "";
		String tm = DateUtil.now();
		try {
			fname = FileUtils.getfilename(urlt);
			e.set("filename", fname);
			e.set("url", urlt);
			e.set("filesize", FileUtils.getfilesize(urlt));
			e.set("downstatus", "正在下载");
			e.set("existstatus", "1");
			e.set("time", tm);
		} catch (Exception w) {
			// TODO: handle exception
			MessageDialog.openInformation(shell, "下载失败", "请输入准确的下载地址!");
			return;
		}

		// 前面判断文件没有问题马上入库，生产一个任务id
		Integer downid = null;
		Record kME = Db.findFirst("select * from down where url=? ;", urlt);
		if (null != kME) {
			MessageDialog.openInformation(shell, "该文件已经下载过了", "该文件已经下载过了请选择其他文件");
			return;
		}
		if (Db.save("down", e)) {
			MessageDialog.openInformation(shell, "下载开始", "文件已经开始下载,请在下载列表查看!");
			Record k = Db.findFirst("select * from down where url=? and time=?;", urlt, tm);
			downid = k.getInt("id");
			downidk = downid;
		}
		Record r = Db.findFirst("select * from config where name='mulu'");
		DownFileInfoBean bean = new DownFileInfoBean(urlt, r.getStr("value"), fname, 5, true, null);

		DownFileFetch fileFetch = null;
		try {
			// downidk = downid;
			fileFetch = new DownFileFetch(bean, downid);
			fileFetch.addListener(new DownListener() {
				public void success() {
					System.out.println("下载成功!来自回调监控");

					ThreadPool.deletethread(downidk, StaticInfo.ok);
					// downidk = null;
				}
			});
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		ThreadPool.addthread(fileFetch, downid, shell);

		// 开启按钮
		btbegin.setEnabled(true);
		btstop.setEnabled(true);

	}
}
